import SwiftUI
import SPGlassKit
#if canImport(MapKit)
import MapKit
#endif

public struct GlassMapControlsExample: GlassExample {
    public static let componentID = "glass-map-controls"
    @State private var engine = SampleMapEngine()
    #if canImport(MapKit)
    @State private var usesMapKit = false
    @State private var mapKitEngine = GlassMapKitEngine(
        position: .camera(MapCamera(centerCoordinate: CLLocationCoordinate2D(latitude: 45.4215, longitude: -75.6972), distance: 6_000, heading: 30))
    )
    #endif

    public init() {}

    public var body: some View {
        VStack(spacing: 12) {
            #if canImport(MapKit)
            Toggle("Use the MapKit adapter (loads map tiles)", isOn: $usesMapKit)
                .padding(.horizontal)
            if usesMapKit {
                mapKitMap
            } else {
                placeholderMap
            }
            #else
            placeholderMap
            #endif
        }
    }

    /// A provider-independent engine: the controls only see `GlassMapEngine`.
    private var placeholderMap: some View {
        SampleMapBackdrop(heading: engine.heading ?? 0, zoom: engine.zoomScale)
            .overlay(alignment: .topTrailing) {
                GlassMapControls(engine: engine) {
                    GlassCompass(heading: engine.heading) { engine.resetNorth() }
                    GlassIconButton(systemImage: "rotate.right", accessibilityLabel: "Rotate the sample map") {
                        engine.rotate(by: 45)
                    }
                }
                .padding()
            }
            .overlay(alignment: .bottom) {
                GlassMapControls(canZoomIn: engine.canZoomIn, canZoomOut: engine.canZoomOut, axis: .horizontal, size: .small) {
                    engine.zoomIn()
                } onZoomOut: {
                    engine.zoomOut()
                }
                .padding(.bottom, 40)
            }
    }

    #if canImport(MapKit)
    private var mapKitMap: some View {
        Map(position: $mapKitEngine.position)
            .onMapCameraChange(frequency: .continuous) { context in
                mapKitEngine.cameraChanged(context.camera)
            }
            .overlay(alignment: .topTrailing) {
                GlassMapControls(engine: mapKitEngine)
                    .padding()
            }
    }
    #endif
}

#Preview("GlassMapControls") { GlassMapControlsExample().glassTheme(.ocean) }
